<script setup lang="ts">
import { ref, watch,nextTick,onBeforeUnmount} from 'vue'
import { primaryColor_hex } from '@/theme/config'
import { deepClone } from '@/common/utils'
import { onMounted } from 'vue'
import sortable from 'sortablejs'

const props = withDefaults(
	defineProps<{
		list: { [key: string]: any }
		idKeyName?: string
		fixedColWidth?: string | number
	}>(),
	{
		idKeyName: 'key',
		fixedColWidth: '',
	}
)

const emits = defineEmits(['confirm'])

const visible = ref(false)
const preCheckedList = ref<string[]>([])
const checkedList = ref<string[]>([])
const checkedAll = ref(false)
const halfchecked = ref(false)
const initList = ref<objType[]>([])
const list = ref<objType[]>([])
const idKey = props.idKeyName
const listElRef = ref()
const sortKeys=ref<string[]>([])
const initCheckedList=ref<string[]>([])
let sortableInstance:any

watch(
	() => props.list,
	(v) => {},
	{ immediate: false }
)

watch(
	checkedList,
	(list) => {
		//console.log(list,list.length)
		if (!list.length) {
			checkedAll.value = false
			halfchecked.value = false
		} else {
			if (list.length == initList.value.length) {
				halfchecked.value = false
				checkedAll.value = true
			} else {
				checkedAll.value = false
				halfchecked.value = true
			}
		}
	},
	{ immediate: true }
)

watch(visible,(v)=>{
   if(v && !listElRef.value){
	 nextTick(()=>{
		setTimeout(()=>{
			initSortable()
		},101)
	 })
   }
})

onMounted(() => {
	initList.value = deepClone(props.list)
	list.value = deepClone(props.list)
	list.value.forEach((v) => {
		if (!(Object.keys(v).includes('checked') && !v.checked)) checkedList.value.push(v[idKey])
	})
    initCheckedList.value=checkedList.value
	if (checkedList.value.length == initList.value.length) {
		halfchecked.value = false
		checkedAll.value = true
	}
	preCheckedList.value = checkedList.value
 // initSortable()
})

onBeforeUnmount(()=>{
   removeSortable()
})

function initSortable (){
	const dragArea = listElRef.value.$el
	const ops = {
		animation: 100,
		dataIdAttr: 'itemId',
		handle:'.tcs-draggable',
		onEnd: (_evt: any) => {
			sortKeys.value=sortableInstance.toArray()
			// console.log(sortableInstance.toArray())
		},
	}
	//初始化
	sortableInstance = sortable.create(dragArea, ops)
	// console.log(sortableInstance)
}

function removeSortable(){
	sortableInstance && sortableInstance.destroy && sortableInstance.destroy()
	sortableInstance=null
}

function handleCheckedChange(e: any) {
	//console.log(e)
}

function handleCheckedAllChange(e: any) {
	// console.log(e)
	checkedList.value = []
	halfchecked.value = false
	if (e)
		list.value.forEach((v) => {
			checkedList.value.push(v[idKey])
		})
	else
		list.value.forEach((v) => {
			if (v.disabled) checkedList.value.push(v[idKey])
		})
}


function hasChange(){
	if(sortKeys.value.length){
		const _checkList:string[]=[]
		sortKeys.value.forEach((v:string)=>{
			if(checkedList.value.includes(v)) _checkList.push(v)
		})
		checkedList.value=_checkList
	}
	if (JSON.stringify(preCheckedList.value) == JSON.stringify(checkedList.value)) return false
	return true
}

function handleConfirm() {
	visible.value = false
	if(!hasChange()) {sortKeys.value=[];return}
	// console.log('333333333')
	const listMap:objType={}
	list.value.forEach(v=>listMap[v[idKey]]=v)
	const temp_list:objType[]=[]
	checkedList.value.forEach(id=>{
		 const item=listMap[id] 
         if(item)temp_list.push(item)
	})
	const _list = deepClone(temp_list)
	//if(props.fixedColWidth) _list[_list.length-1].width=props.fixedColWidth
	emits('confirm', _list)
	preCheckedList.value = checkedList.value
	sortKeys.value=[]
}


function handleReset() {
	visible.value = false
	checkedList.value=initCheckedList.value
	if(!hasChange()) {sortKeys.value=[];return}
	// console.log('111111111')
	preCheckedList.value=checkedList.value
	sortKeys.value=[]
	const _list=deepClone(initList.value)
	//if(props.fixedColWidth) _list[_list.length-1].width=props.fixedColWidth
	emits('confirm', _list);
	[...listElRef.value.$el.children].forEach(v=>v.remove())
	list.value=[]
	nextTick(()=>{list.value=deepClone(initList.value)})
}
</script>

<template>
	<a-popover placement="bottomLeft" trigger="click" v-model:visible="visible">
		<template #default>
			<a-button>表格列设置</a-button>
		</template>

		<template #content>
			<div class="content" style="min-width: 115px">
				<div class="checkedAll" style="margin-bottom: 15px">
					<a-checkbox :indeterminate="halfchecked" v-model:checked="checkedAll" @change="handleCheckedAllChange">
						<span :style="{ color: primaryColor_hex }">全选/反选</span>
					</a-checkbox>
				</div>

				<div class="checkedList" style="overflow: auto; max-height: 250px">
					<a-checkbox-group v-model:value="checkedList" @change="handleCheckedChange" ref="listElRef">
						<div :class="{checkedItem:true,'tcs-draggable':!item.disabled}" v-for="item in list" style="margin: 5px 0" :itemid="item[idKey]">
							<a-checkbox :key="item[idKey]" :value="item[idKey]" :disabled="item.disabled">
								{{ item.title }}
							</a-checkbox>
						</div>
					</a-checkbox-group>
				</div>

				<div class="operation">
					<div class="right" style="display: flex">
						<a-button size="small" @click="handleReset">重置</a-button>
						<a-button type="primary" size="small" @click="handleConfirm">确定</a-button>
					</div>
				</div>
			</div>
		</template>
	</a-popover>
</template>

<style scoped lang="less">
.operation {
	display: flex;
	justify-content: right;
	margin-top: 10px;
}
</style>
